#!/bin/bash
set -e

monacoRef=$(cat package.json | jq -r '.config.monaco.ref')

package_json="`pwd`/package.json"
output_directory="`pwd`/monaco-editor"
version_info=$output_directory/version.info

if [[ -e $version_info && $(cat $version_info) == $monacoRef ]]; then
    echo "monaco-editor version $monacoRef is already installed. Aborting..."
    exit 0
else
    echo "monaco-editor version $monacoRef is not available. Installing..."
fi

monaco_build_directory=`mktemp -d`
echo "Downloading monaco-editor languages $monacoRef in $monaco_build_directory..."
rm -rf $output_directory
mkdir -p $output_directory
curl -L --max-redirs 5 https://github.com/Microsoft/monaco-editor/tarball/$monacoRef | tar -xz -C $monaco_build_directory --strip-components=1
monacoVersion=$(cat "$monaco_build_directory/package.json" | jq -r '.["version"]')
cat <<< "$(jq ".config.monaco.version = \"$monacoVersion\"" $package_json)" > $package_json

cd $monaco_build_directory
npm ci

# Copy editor types
npm run build-monaco-editor
cp out/monaco-editor/esm/vs/editor/editor.api.d.ts $output_directory/editor.api.d.ts
cp -R out/monaco-editor/esm/vs/basic-languages $output_directory/basic-languages
cp -R out/monaco-editor/esm/vs/language $output_directory/language

echo $monacoRef > $version_info

# Cleaning
rm -rf $monaco_build_directory
